using System;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.Linq;

namespace StubsDemo.SystemUnderTest.ViewModels
{
    public class CustomerListViewModel
    {
        private readonly ICustomerRepository repository;
        private int autoRefreshInterval;
        private ObservableCollection<CustomerViewModel> allCustomers;

        internal CustomerListViewModel()
        {
            autoRefreshInterval = 0;
            allCustomers = new ObservableCollection<CustomerViewModel>();
        }

        public CustomerListViewModel(ICustomerRepository repository)
            : this()
        {
            this.repository = repository;
        }

        public int AutoRefreshInterval
        {
            get { return autoRefreshInterval; }
            set
            {
                autoRefreshInterval = value;
                if (autoRefreshInterval > 0)
                    StartRefreshTimer();
            }
        }

        private void StartRefreshTimer()
        {
            var timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, autoRefreshInterval) };
            timer.Tick += (sender, args) => RefreshCustomerCollection();
            timer.Start();
        }

        private void RefreshCustomerCollection()
        {
            var customerViewModels = repository.GetAll().Select(cust => new CustomerViewModel(cust, repository));
            AllCustomers.Clear();
            foreach (var customerViewModel in customerViewModels)
                AllCustomers.Add(customerViewModel);
        }

        public ObservableCollection<CustomerViewModel> AllCustomers
        {
            get { return allCustomers; }
        }
    }
}